$(function () {

    var topicId = $('#id').val();

    listTopicReply(1);

    // 加载班级数据
    function listTopicReply(pageNo) {
        var params = {'topicId': topicId, 'rootId': 0};
        params = JSON.stringify(params);
        var obj = {
            url: baseloaction + '/web/classes/topic/ajaxTopicReplyList',
            contextId: 'classes-topic-reply',
            params: params,
            pageNo: pageNo,
            pageCall: listTopicReply
        };
        getPageAjaxData(obj);
        lazyUserImage();
    }


    $('body')
        .on('click', 'button[data-cancel]', function () {
            $(this).parents('div[data-target]').addClass('hide');
        })
        .on('click', 'a[data-target]', function () {
            if ($('#replyBtn').is(':disabled')) {
                return;
            }
            var target = $(this).data('target');
            $('div[data-target=' + target + ']').removeClass('hide');
        })
        .on('click', 'button[data-reply]', function () {
            if ($('#replyBtn').is(':disabled')) {
                return;
            }
            saveTopicReply(this);
        }).on('keyup','div[data-target] textarea[data-context]',function(){
            var that =$(this);
            if(that.val().length>=200){
                that.val( that.val().substring(0,200));
                icModale(0,'',"最多可输入200个字");
            }

    });

    // 保存
    function saveTopicReply(obj) {
        isLogin(function () {
            var targetId = $(obj).parents('div[data-target]').data('target');
            var content = $(obj).parents('div[data-target]').find('textarea[data-context]').val();
            var params = {topicId: topicId, 'targetId': targetId, 'content': content};
            params = JSON.stringify(params);
            $.ajax({
                url: baseloaction + "/web/classes/topic/saveTopicReply",
                data: params,
                dataType: 'json',
                type: 'post',
                contentType: 'application/json;charset=utf-8',
                success: function (response) {
                    if (response.success) {
                        icModale(0, '', response.message);
                        listTopicReply(1);
                        $(obj).parents('section').prev().find('textarea[data-context]').val('');
                        var html = $('#topic-reply-count').html();
                        var number = parseInt(/[\d]+/g.exec(html));
                        $('#topic-reply-count').html('(' + (number + 1) + ')');
                    } else {
                        icModale(0, '', response.message);
                        $(obj).parent().find('span.mr10').removeClass('hide')
                            .find('small.c-danger')
                            .html('<i class="fa fa-exclamation-circle"></i> ' + response.message);
                    }
                }
            });
        })
    }

});